package com.guoxue.action.front;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guoxue.action.common.SCSettingStaticName;
import com.guoxue.consts.SCUser;
import com.guoxue.domain.AdvertisementVo;
import com.guoxue.domain.BookConfigVo;
import com.guoxue.domain.ChapterConfigVo;
import com.guoxue.domain.ExpertReadingVo;
import com.guoxue.domain.FollowsVo;
import com.guoxue.domain.GoodBookRecordVo;
import com.guoxue.domain.IOSDeviceVo;
import com.guoxue.domain.LevelConfigVo;
import com.guoxue.domain.PersonPushVo;
import com.guoxue.domain.PlanChapterConfigVo;
import com.guoxue.domain.PlanConfigVo;
import com.guoxue.domain.PlanProgressVo;
import com.guoxue.domain.PlayerProgressVo;
import com.guoxue.domain.RecordConfigVo;
import com.guoxue.domain.TapesRecordsVo;
import com.guoxue.domain.TapesShareVo;
import com.guoxue.domain.UserCoinsVo;
import com.guoxue.domain.UserToOSSAudioVo;
import com.guoxue.domain.UserVo;
import com.guoxue.model.ChapterConfig;
import com.guoxue.model.ExpertRead;
import com.guoxue.model.GiftList;
import com.guoxue.model.GiveAwayGiftList;
import com.guoxue.model.RedisRecentUser;
import com.guoxue.service.IAdvertisementService;
import com.guoxue.service.IBookConfigService;
import com.guoxue.service.IChapterConfigService;
import com.guoxue.service.IExpertReadingService;
import com.guoxue.service.IFollowsService;
import com.guoxue.service.IGiftListService;
import com.guoxue.service.IGoodBookRecordService;
import com.guoxue.service.IIOSDeviceService;
import com.guoxue.service.ILevelConfigService;
import com.guoxue.service.IPersonPushService;
import com.guoxue.service.IPlanChapterConfigService;
import com.guoxue.service.IPlanConfigService;
import com.guoxue.service.IPlanProgressService;
import com.guoxue.service.IPlayerProgressService;
import com.guoxue.service.IRecordConfigService;
import com.guoxue.service.ITapesRecordsService;
import com.guoxue.service.ITapesShareService;
import com.guoxue.service.IUserCoinsService;
import com.guoxue.service.IUserService;
import com.guoxue.service.IUserToOSSAudioService;
import com.guoxue.util.LoadConfigProperties;
import com.guoxue.util.LoggerUtil;
import com.guoxue.util.OSSUtil;
import com.guoxue.util.OtherUtils;
import com.guoxue.util.PushUtil;
import com.guoxue.util.RedisUtil;

import redis.clients.jedis.Jedis;

/**
 * 诵读功能模块接口
 * 
 * @author young
 *
 */
@Controller
@RequestMapping("Read")
public class ReadAction extends BaseAction {

	@Resource
	private IPlayerProgressService playerService;
	@Resource
	private IPlanProgressService planService;
	@Resource
	private IPlanConfigService planConfigService;
	@Resource
	private IBookConfigService bookService;
	@Resource
	private IUserService userService;
	@Resource
	private ITapesRecordsService tapesService;
	@Resource
	private IExpertReadingService expertReadingService;
	@Resource
	private IChapterConfigService chapterConfigService;
	@Resource
	private IRecordConfigService recordConfigService;
	@Resource
	private ILevelConfigService levelConfigService;
	@Resource
	private IPlanChapterConfigService PlanChapterService;
	@Resource
	private OSSUtil oss;
	@Resource
	private IGoodBookRecordService goodBookRecordService;
	@Resource
	private ITapesRecordsService tapesRecordsService;
	@Resource
	private IGiftListService iGiftListService;
	@Resource
	private IFollowsService followsService;
	@Resource
	private ITapesShareService shareService;
	@Resource
	private IPersonPushService personPushService;
	@Resource
	private IIOSDeviceService IOSDeviceService;
	@Resource
	private PushUtil pushUtil;
	@Resource
	private IAdvertisementService adsService;
	@Resource
	private IUserToOSSAudioService userToOSSAudioService;
	@Resource
	private IUserCoinsService userCoinsService;
	/**
	 * 进度上传接口
	 * 
	 * @param req
	 * @param resp
	 * @param planId
	 * @param sentence
	 * @param uid
	 * @param smallRound
	 * @return
	 */
	@RequestMapping("/planCommit")
	@ResponseBody
	public JSON playerProgressCommit(HttpServletRequest req, HttpServletResponse resp, Integer planId, Integer sentence,
			Integer uid, Integer smallRound) {
		try {
			if (planId == null || sentence == null) {
				return Message(ERROR, "参数不全请检查参数", null);
			}
			if (uid == null) {
				return Message(ERROR, "用户id未上传", null);
			}
			if (smallRound == null) {
				smallRound = 0;
			}
			/*-----------判断用户是否存在----------------*/
			UserVo user = userService.getUserByKey(uid);
			if (user == null) {
				return Message(ERROR, "获取用户信息失败", null);
			}
			// TODO:修改为从内存中查询 do|当前计划的基本信息
			PlanConfigVo pc = LoadConfigProperties.planConfigMap.get(planId);
			PlanChapterConfigVo pChapter = LoadConfigProperties.planChapterConfigMap.get(pc.getPlanChapterdy());
			if (pc == null || pChapter == null) {
				return Message(ERROR, "获取当前计划信息失败", null);
			}
			/*----------查询当前用户有无奖牌和经验记录-----------------*/
			PlayerProgressVo pp = playerService.getPlayerProgressByUid(user.getId());
			if (pp == null) {
				pp = new PlayerProgressVo();
				pp.setMedals(0);
				pp.setExp(0);
				pp.setUid(user.getId());
			}
			/*----------查询当前用户有无该计划下的诵读记录-----------------*/
			PlanProgressVo ppr = planService.getPlanByUserAndPlanId(user.getId(), planId);
			if (ppr == null) {
				ppr = new PlanProgressVo();
				ppr.setCurrentPlanId(planId);
				ppr.setCurrentSentence(0);
				ppr.setCurrentReadCount(0);
				ppr.setCurrentReadRound(0);
				ppr.setSmallRound(0);
				ppr.setUid(user.getId());
			}
			/*----------完成本次提交改变当前用户得经验、奖牌、解锁下一阶段及每个阶段的读取情况-----------------*/
			int medal = 0;// 获得多少奖牌
			int exp = 0;// 获得多少经验
			int round = 0;// 第几轮
			int newUnlock = 0;// 解锁
			boolean levelUp = false;// 是否升级
			/*----------该计划本轮未完成的提交1.第一轮未完成的诵读2.N+1轮未完成的诵读-----------------*/
			if (pChapter.getEndWordId() >= sentence) {
				ppr.setCurrentSentence(sentence);
				if (pChapter.getEndWordId() == sentence) {
					ppr.setSmallRound(ppr.getSmallRound() + 1);
					ppr.setCurrentReadCount(ppr.getCurrentReadCount() + 1);
				}

			}
			/*----------该计划本轮完成的提交1.首次完成提交2.N+1次完成提交-----------*/
			if (pc.getCount() == ppr.getSmallRound()) {
				ppr.setCurrentReadRound(ppr.getCurrentReadRound() + 1);
				// 判断是否是某本书的第一个计划，如果是，则不需要创建某本书的首个计划--------------------排除计划的首个阶段再次存放
				boolean unLockNew = true;
				PlanProgressVo ppCheck = planService.getPlanByUserAndPlanId(uid, planId + 1);
				if (ppCheck != null) {
					unLockNew = false;
				}
				// -------------------------------------------------------------------

				/*----------判断本轮完成的是首次完成-----------*/
				if (ppr.getCurrentReadRound() == 1) {
					if (unLockNew) {
						PlanProgressVo unlockPlan = new PlanProgressVo();
						unlockPlan.setCurrentPlanId(planId + 1);
						unlockPlan.setCurrentSentence(0);
						unlockPlan.setCurrentReadCount(0);
						unlockPlan.setCurrentReadRound(0);
						unlockPlan.setSmallRound(0);
						unlockPlan.setUid(user.getId());
						unlockPlan.setMedal(0);
						unlockPlan.setCommitDate(OtherUtils.getCurrentDate());
						planService.savePlan(unlockPlan);
					}
					/*-------------------解锁新的计划阶段--------------------*/
					newUnlock = planId + 1;
					exp = pc.getFirstExp();
					medal = pc.getFirstMedal();
				} else {
					exp = pc.getExp();
					medal = pc.getMedal();
				}
				ppr.setSmallRound(0);// 本次完成重新计数
				ppr.setCurrentReadCount(0);
			}
			ppr.setCommitDate(OtherUtils.getCurrentDate());
			/*-------------------更新当前用户的当前阶段读取情况---------------*/
			ppr.setMedal(medal);
			planService.savePlan(ppr);
			/*-------------------更新当前用户的奖牌和经验---------------*/
			LevelConfigVo level = levelConfigService.getLevelByExp(pp.getExp());
			int newlevel = levelConfigService.getLevelByExp(pp.getExp() + exp).getLevel();
			if (level.getLevel() < newlevel) {
				levelUp = true;
			}
			LevelConfigVo lv = levelConfigService.getMaxLevel();
			if ((pp.getExp() + exp) >= lv.getExp()) {
				pp.setExp(lv.getExp());
			} else {
				pp.setExp(pp.getExp() + exp);
			}
			pp.setMedals(pp.getMedals() + medal);
			playerService.savePlayerProgress(pp);
			/*----------------向请求返回数据----------------------------------*/
			long complete = planService.getCompleteCount(round, planId); // 计算当前阶段击败人数
			long total = planService.getCount(planId);
			double percent = 1 - (complete / total);
			NumberFormat nt = NumberFormat.getPercentInstance();
			nt.setMinimumFractionDigits(0);
			JSONObject obj = new JSONObject();
			obj.put("Numberofdefeats", nt.format(percent));
			obj.put("medal", medal);
			obj.put("exp", exp);
			obj.put("levelUp", levelUp);
			obj.put("unlockId", newUnlock);
			return Message(SUCCESS, "数据提交成功", obj);// 返回当前获取经验与奖牌数
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "用户数据提交异常");
		}
	}

	/**
	 * 或缺用户信息以及相关计划进度信息
	 * 
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping("/getProgress")
	@ResponseBody
	public JSON getProgress(HttpServletRequest req, HttpServletResponse resp, Integer uid) {
		try {
			JSONObject data = new JSONObject();
			JSONObject obj = new JSONObject();
			List<AdvertisementVo> ls = adsService.getAdvertisementList();
			for (AdvertisementVo av : ls) {
				av.setPic(oss.getUrl(bucket, av.getPic(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			data.put("ads", ls);
			if (uid == null) {
				return Message(ERROR, "未提交用户id", null);
			}
			UserVo user = userService.getUserByKey(uid);
			if (user != null) { // 获取用户真实进度
				PlayerProgressVo pp = playerService.getPlayerProgressByUid(uid);
				List<BookConfigVo> books = new ArrayList<BookConfigVo>(LoadConfigProperties.bookConfigMap.values());
				JSONObject plan = null;
				JSONArray conf = new JSONArray();
				for (BookConfigVo book : books) { // 按单个计划获取所配置的总奖牌数、作者名，书名等相关信息
					int total = 0;
					int begin = book.getBeginPlanId();
					int end = book.getEndPlanId();
					int readers = planService.getReadersCount(user.getId(), begin, end);
					// TODO:修改为从内存资源中查询 do
					List<PlanConfigVo> lpc = new ArrayList<PlanConfigVo>();
					for (int i = begin; i <= end; i++) {
						lpc.add(LoadConfigProperties.planConfigMap.get(i));
					}
					plan = new JSONObject();
					plan.put("bookId", book.getBookId());
					plan.put("bookName", book.getBookName());
					plan.put("bookWriter", book.getWriter());
					plan.put("bookReader", book.getReader());
					for (PlanConfigVo pl : lpc) {
						total = total + pl.getFirstMedal();
					}
					plan.put("total", total);
					plan.put("currentReader", readers); // 获取当前该书在读人数
					List<PlanProgressVo> lp = planService.getUserPlansByPlanId(user.getId(), book.getBeginPlanId(),
							book.getEndPlanId());
					if (lp.size() == 0) {
						plan.put("acquireMedal", 0);
					} else {
						plan.put("acquireMedal", pp.getMedals());
					}
					conf.add(plan);
				}
				int leve = 1;
				if (pp != null) { // 获取用户等级，总奖牌数，经验，头像等相关信息
					List<LevelConfigVo> levels = new ArrayList<LevelConfigVo>(
							LoadConfigProperties.levelConfigMap.values());
					int CurExp = pp.getExp();
					for (int x = 0; x < levels.size(); x++) {
						if (CurExp - levels.get(x).getExp() < 0) {
							leve = x;
							break;
						}
						CurExp = CurExp - levels.get(x).getExp();
					}
					int nextlevelExp = LoadConfigProperties.levelConfigMap.get(leve + 1).getExp(); // 获取下一级所需经验;
					if (leve == 1) {
						obj.put("exp", 0);
						obj.put("nextExp", nextlevelExp);
					} else {
						obj.put("exp", CurExp);
						obj.put("nextExp", nextlevelExp);
					}
					obj.put("nickName", user.getNickName());
					obj.put("level", leve);
					obj.put("headImg", isEmpty(user.getImgUrl()) ? null
							: oss.getUrl(bucket, user.getImgUrl(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
					obj.put("sex", user.getSex());
					obj.put("stauts", user.getStatus());
					data.put("userInfo", obj);
					data.put("progress", conf);
					return Message(SUCCESS, "获取用户信息成功", data);
				} else {
					obj.put("nextExp", LoadConfigProperties.levelConfigMap.get(2).getExp());
					obj.put("nickName", user.getNickName());
					obj.put("level", leve);
					obj.put("stauts", user.getStatus());
					obj.put("exp", 0);
					obj.put("headImg", isEmpty(user.getImgUrl()) ? null
							: oss.getUrl(bucket, user.getImgUrl(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
					obj.put("sex", user.getSex());
				}
				data.put("userInfo", obj);
				data.put("progress", conf);
				return Message(SUCCESS, "获取用户信息成功", data);
			} else {
				return Message(ERROR, "获取用户失败", null);
			}
		} catch (Exception e) {
			LoggerUtil.logInfo(e, "获取用户信息异常");
		}
		return null;
	}

	/**
	 * 获取用户单个计划阶段信息
	 * 
	 * @param req
	 * @param resp
	 * @param bookId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getPlans")
	public JSON getPlans(HttpServletRequest req, HttpServletResponse resp, Integer bookId, Integer uid) {
		try {
			if (uid == null) {
				return Message(ERROR, "为提交用户id", null);
			}
			UserVo user = userService.getUserByKey(uid);
			if (user == null) {
				return Message(ERROR, "不存在该用户", null);
			}
			if (bookId == null) {
				return Message(ERROR, "未提交书籍id", null);
			} else {
				BookConfigVo book = LoadConfigProperties.bookConfigMap.get(bookId);
				if (book == null) {
					return Message(ERROR, "未查找到当前书籍", null);
				} else {
					// TODO:修改为从内存资源中查询 do
					List<PlanConfigVo> lp = new ArrayList<PlanConfigVo>(); // 按单个计划获取对应计划配置
					for (int i = book.getBeginPlanId(); i <= book.getEndPlanId(); i++) {
						lp.add(LoadConfigProperties.planConfigMap.get(i));
					}
					if (lp.size() > 0) {
						JSONArray data = new JSONArray();
						PlanProgressVo ppv = planService.getLastCommit(user.getId());// 获取用户最后一次操作信息
						if (ppv == null) {
							ppv = new PlanProgressVo();
						}
						for (PlanConfigVo pc : lp) {
							JSONObject obj = new JSONObject();
							obj.put("planId", pc.getPlanId());
							obj.put("planReadCount", pc.getCount());
							obj.put("planType", pc.getPlanType());
							obj.put("planTitle", pc.getPlanTitle());
							PlanProgressVo pp = planService.getUserPlanByUidAndPlanId(user.getId(), pc.getPlanId()); // 获取对应阶段用户信息
							int currentReadCount = 0; // 当前读一轮中的次数
							int currentReadRound = 0; // 当前的轮数
							int nextRound = 0; // 接下来该读第几轮

							// 当前轮没有数据（每本书第一个阶段）
							if (pp == null) {
								obj.put("currentReadCount", currentReadCount);
								obj.put("currentReadRound", currentReadRound + 1);
								obj.put("currentSentence", null);
								obj.put("Numberofdefeats", 0 + "%");
								obj.put("unlock", false);
								obj.put("reading", false);
								obj.put("nextRound", 1);
							} else {
								// 计算当前阶段击败人数---------------------------
								long complete = planService.getCompleteCount(pp.getCurrentReadRound(), pc.getPlanId());
								long total = planService.getCount(pc.getPlanId());
								double percent = 1 - (complete / total);
								NumberFormat nt = NumberFormat.getPercentInstance();
								nt.setMinimumFractionDigits(0);
								obj.put("Numberofdefeats", nt.format(percent));
								// -----------------------------------------
								if (pp.getCurrentReadRound() == 0 && pp.getCurrentReadCount() > 0) {
									currentReadRound = 1;
									nextRound = currentReadRound;
								}
								if (pp.getCurrentReadRound() > 0 && pp.getCurrentReadCount() == 0) {
									currentReadRound = pp.getCurrentReadRound();
									nextRound = currentReadRound + 1;
								}
								if (pp.getCurrentReadRound() > 0 && pp.getCurrentReadCount() > 0) {
									currentReadRound = pp.getCurrentReadRound() + 1;
									nextRound = currentReadRound;
								}
								if (pp.getCurrentReadRound() == 0 && pp.getCurrentReadCount() == 0) {
									currentReadRound = 1;
									nextRound = currentReadRound;
								}
								obj.put("currentReadCount", pp.getCurrentReadCount());
								obj.put("currentReadRound", currentReadRound);
								obj.put("nextRound", nextRound);
								obj.put("currentSentence", pp.getCurrentSentence());
								obj.put("unlock", true);
								if (ppv.getId() == pp.getId()) {
									obj.put("reading", true);
								} else {
									obj.put("reading", false);
								}
							}
							if (pc.getPlanId() == book.getBeginPlanId()) {
								obj.put("unlock", true);
							}
							data.add(obj);
						}
						return Message(SUCCESS, "获取阶段列表成功", data);
					} else {
						return Message(ERROR, "为查找到当前计划", null);
					}
				}
			}
		} catch (Exception e) {
			LoggerUtil.logInfo(e, "获取用户信息异常");
		}
		return null;
	}

	/**
	 * 
	 * @param req
	 * @param resp
	 * @param tapes
	 * @param size
	 * @param flag
	 * @param comment
	 * @param uid
	 * @param chapter
	 *            oss存放key
	 * @param size
	 *            文件大小
	 * @param flag
	 *            关联章节id
	 * @param comment
	 *            评论
	 * @param uid
	 *            用户id
	 * @param chapter
	 *            章节名
	 * @return
	 */
	@RequestMapping("/tapesCommit")
	@ResponseBody
	/**
	 * 客户端通知服务器,上传了音频文件到oss
	 * 
	 * @param req
	 * @param resp
	 * @param tapes
	 *            音频文件id?
	 * @param size
	 *            上传的音频文件的大小
	 * @param flag
	 *            音频文件所属的章节或计划?
	 * @param comment
	 *            用户备注?
	 * @param uid
	 *            用户id
	 * @param chapter
	 *            录音章节名(章节的标题)(应该不需要记录?)
	 * @return
	 */
	public JSON tapesCommit(HttpServletRequest req, HttpServletResponse resp, String tapes, String flag,
			String comment, String chapter) {
		final int uid = SCUser.getUidFromReq(req);
		try {
			if (isEmpty(tapes)) {
				return Message(ERROR, "上传key不能为空", null);
			}
			if (isEmpty(flag)) {
				return Message(ERROR, "未指定所属章节或计划", null);
			}
			if (isEmpty(chapter)) {
				return Message(ERROR, "录音章节名为空", null);
			}
			/*------------查询当前数据是否准确-------------------*/
			UserToOSSAudioVo uTa=userToOSSAudioService.getUserToAudioByUid(uid,tapes);
			if(uTa==null){
				return Message(ERROR, "当前上传数据有误请检查", null);
			}
			int size=uTa.getLastSize();
			//完成计数并清除临时表数据
			UserCoinsVo totalTapes = userCoinsService.getUserCoinsById(uid);
			totalTapes.setTotalLine(totalTapes.getTotalLine()+1);
			totalTapes.setTotalSize(totalTapes.getTotalSize()+size);
			userCoinsService.saveUserCoins(totalTapes);
			userToOSSAudioService.deleteUserToAudioByUid(uTa);			
			// ----kanghongbo重新构造------
			TapesRecordsVo tr = new TapesRecordsVo();
			tr.setTapes(tapes);
			tr.setUid(uid);
			tr.setCommitTime(OtherUtils.getCurrentDate());
			tr.setSize(size);
			tr.setFlag(flag);
			tr.setUserComment(comment);
			tr.setChapter(chapter);
			tapesService.saveTapesRecords(tr);
			// -------------------------
			// 推送消息给自己的好友
			UserVo user = userService.getUserByKey(uid);
			PersonPushVo personPush = new PersonPushVo();
			personPush.setUserId(String.valueOf(uid));
			personPush.setCreateTime(OtherUtils.getCurrentDate());
			personPush.setTapesId(flag);
			String message = "***" + user.getNickName() + "上传了《***" + chapter + "》，点击查看";
			personPush.setContent(message);
			personPushService.savePersonPush(personPush);
			// 推送消息
			List<FollowsVo> followsList = followsService.getFollowedList(uid);
			if (followsList.size() > 0) {
				List<String> IOSDeviceList = new ArrayList<String>();
				for (FollowsVo f : followsList) {
					IOSDeviceVo IOSDevice = IOSDeviceService.getIOSDevice(f.getFollowed(), 1);
					if (null != IOSDevice) {
						IOSDeviceList.add(IOSDevice.getDeviceToken());
					}
				}
				if (IOSDeviceList.size() > 0) {
					pushUtil.sendPush(IOSDeviceList, message, false, null);
				}
			}
			return Message(SUCCESS, "上传成功", tapes);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "上传异常");
		}

	}

	/**
	 * 记录佳作播放到那个章节
	 * 
	 * @param req
	 * @param resp
	 * @param uid
	 *            用户id
	 * @param workId
	 *            佳作id
	 * @param charpterId
	 *            章节id
	 * @param type
	 *            1.佳作2.作品
	 * @param userId
	 *            被听人id
	 * @return
	 */
	@RequestMapping("/GoodBookRecordCommit")
	@ResponseBody
	public JSON GoodBookRecordCommit(HttpServletRequest req, HttpServletResponse resp, Integer uid, String workId,
			String charpterId, Integer type, Integer userId) {
		try {
			if (null == uid) {
				return Message(ERROR, "未传用户id", null);
			}
			if (null == workId) {
				return Message(ERROR, "未传作品id", null);
			}
			if (null == userId) {
				return Message(ERROR, "未传用户id", null);
			}
			if (type == 1) {
				if (null == charpterId) {
					return Message(ERROR, "未传作品章节id", null);
				}
			}
			GoodBookRecordVo GoodBookRecordVo = goodBookRecordService.getGoodBookRecord(uid, workId, type);
			if (null == GoodBookRecordVo) {
				GoodBookRecordVo goodBookRecord = new GoodBookRecordVo();
				goodBookRecord.setCharpterId(charpterId);
				goodBookRecord.setUid(uid);
				goodBookRecord.setWorkId(workId);
				goodBookRecord.setUserId(userId);
				goodBookRecord.setType(type);
				goodBookRecord.setCreateTime(OtherUtils.getCurrentDate());
				goodBookRecordService.saveGoodBookRecord(goodBookRecord);
			} else {
				GoodBookRecordVo.setCreateTime(OtherUtils.getCurrentDate());
				GoodBookRecordVo.setCharpterId(charpterId);
				goodBookRecordService.saveGoodBookRecord(GoodBookRecordVo);
			}
			return Message(SUCCESS, "添加佳作记录成功", null);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "佳作记录异常");
		}

	}

	/**
	 * 获取佳作列表
	 * 
	 * @param req
	 * @param resp
	 * @param uid
	 *            用户id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getGoodBookList")
	public JSON getGoodBookList(HttpServletRequest req, HttpServletResponse resp, Integer uid) {
		try {
			if (null == uid) {
				return Message(ERROR, "未传用户id", null);
			}
			List<ExpertRead> ExpertReadList = new ArrayList<>();
			List<ExpertReadingVo> expertReadingList = expertReadingService.getExpertReadingList();
			for (ExpertReadingVo e : expertReadingList) {
				String url = isEmpty(e.getPhoto1()) ? null
						: oss.getUrl(bucket, e.getPhoto1(), new Date(new Date().getTime() + 3600 * 1000 * 12));
				// e.setPhoto1(isEmpty(e.getPhoto1())?null:oss.getUrl(bucket,
				// e.getPhoto1(), new Date(new Date().getTime() + 3600 * 1000 *
				// 12)));
				e.setPhoto1(url);
				JSONArray array = new JSONArray();
				// array.add(0, isEmpty(e.getPhoto1())?null:oss.getUrl(bucket,
				// e.getPhoto1(), new Date(new Date().getTime() + 3600 * 1000 *
				// 12)));
				if (url != null) {
					array.add(0, url);
				}
				if (!isEmpty(e.getPhoto2())) {
					array.add(isEmpty(e.getPhoto2()) ? null
							: oss.getUrl(bucket, e.getPhoto2(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto3())) {
					array.add(isEmpty(e.getPhoto3()) ? null
							: oss.getUrl(bucket, e.getPhoto3(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto4())) {
					array.add(isEmpty(e.getPhoto4()) ? null
							: oss.getUrl(bucket, e.getPhoto4(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto5())) {
					array.add(isEmpty(e.getPhoto5()) ? null
							: oss.getUrl(bucket, e.getPhoto5(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto6())) {
					array.add(isEmpty(e.getPhoto6()) ? null
							: oss.getUrl(bucket, e.getPhoto6(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto7())) {
					array.add(isEmpty(e.getPhoto7()) ? null
							: oss.getUrl(bucket, e.getPhoto7(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto8())) {
					array.add(isEmpty(e.getPhoto8()) ? null
							: oss.getUrl(bucket, e.getPhoto8(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto9())) {
					array.add(isEmpty(e.getPhoto9()) ? null
							: oss.getUrl(bucket, e.getPhoto9(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto10())) {
					array.add(isEmpty(e.getPhoto10()) ? null
							: oss.getUrl(bucket, e.getPhoto10(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				ExpertRead expertRead = new ExpertRead(array, e);
				GoodBookRecordVo goodBookRecord = goodBookRecordService.getGoodBookRecord(uid,
						String.valueOf(e.getWorkId()), 1);
				if (null != goodBookRecord) {
					expertRead.setCharpterId(String.valueOf(goodBookRecord.getCharpterId()));
				} else {
					expertRead.setCharpterId(String.valueOf(e.getBeginChapterId()));
				}
				ChapterConfigVo c = chapterConfigService.getChapterConfig(e.getBeginChapterId(), e.getEndChapterId());
				RecordConfigVo r = recordConfigService.getRecordConfig(c.getBeginWordId(), c.getEndWordId());
				expertRead.setFile(r.getFile());
				ExpertReadList.add(expertRead);
			}
			// JSONObject json = new JSONObject();
			// json.put("expertReadingList", ExpertReadList);
			return Message(SUCCESS, "获取佳作列表成功", ExpertReadList);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "获取佳作列表失败");
		}
	}

	/**
	 * 获取单个佳作信息
	 * 
	 * @param req
	 * @param resp
	 * @param beginChapterId
	 *            章节起始id
	 * @param endChapterId
	 *            章节结束id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getGoodBookChapterList")
	public JSON getGoodBookChapterList(HttpServletRequest req, HttpServletResponse resp, Integer beginChapterId,
			Integer endChapterId) {
		try {
			if (beginChapterId == null) {
				return Message(ERROR, "未传章节起始id", null);
			}
			if (endChapterId == null) {
				return Message(ERROR, "未传章节结束id", null);
			}
			List<ChapterConfig> chapterConfigList = new ArrayList<>();
			List<ChapterConfigVo> chapterConfigVoList = chapterConfigService.getChapterConfigList(beginChapterId,
					endChapterId);
			for (ChapterConfigVo c : chapterConfigVoList) {
				List<RecordConfigVo> recordConfigVoList = recordConfigService.getRecordConfigList(c.getBeginWordId(),
						c.getEndWordId());
				ChapterConfig chapterConfig = new ChapterConfig();
				chapterConfig.setSentence(recordConfigVoList);
				chapterConfig.setBeginWordId(c.getBeginWordId());
				chapterConfig.setChapterId(c.getChapterId());
				chapterConfig.setChapterName(c.getChapterName());
				chapterConfig.setEndWordId(c.getEndWordId());
				chapterConfigList.add(chapterConfig);
			}
			// JSONObject json = new JSONObject();
			// json.put("chapterConfigList", chapterConfigList);
			return Message(SUCCESS, "获取佳作详情成功", chapterConfigList);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "获取佳作详情失败");
		}
	}

	/**
	 * 搜索佳作列表
	 * 
	 * @param req
	 * @param resp
	 * @param uid
	 *            用户id
	 * @param searchName
	 *            搜索内容
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getGoodBookListSearch")
	public JSON getGoodBookListSearch(HttpServletRequest req, HttpServletResponse resp, String searchName,
			Integer uid) {
		try {
			if (searchName == null) {
				return Message(ERROR, "未获取到搜索内容", null);
			}
			if (null == uid) {
				return Message(ERROR, "未传用户id", null);
			}
			List<ExpertRead> ExpertReadList = new ArrayList<>();
			List<ExpertReadingVo> expertReadingList = expertReadingService.getExpertReadingList(searchName);
			for (ExpertReadingVo e : expertReadingList) {
				String url = isEmpty(e.getPhoto1()) ? null
						: oss.getUrl(bucket, e.getPhoto1(), new Date(new Date().getTime() + 3600 * 1000 * 12));
				// e.setPhoto1(isEmpty(e.getPhoto1())?null:oss.getUrl(bucket,
				// e.getPhoto1(), new Date(new Date().getTime() + 3600 * 1000 *
				// 12)));
				e.setPhoto1(url);
				JSONArray array = new JSONArray();
				// array.add(0, isEmpty(e.getPhoto1())?null:oss.getUrl(bucket,
				// e.getPhoto1(), new Date(new Date().getTime() + 3600 * 1000 *
				// 12)));
				if (!isEmpty(e.getPhoto2())) {
					array.add(isEmpty(e.getPhoto2()) ? null
							: oss.getUrl(bucket, e.getPhoto2(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto3())) {
					array.add(isEmpty(e.getPhoto3()) ? null
							: oss.getUrl(bucket, e.getPhoto3(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto4())) {
					array.add(isEmpty(e.getPhoto4()) ? null
							: oss.getUrl(bucket, e.getPhoto4(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto5())) {
					array.add(isEmpty(e.getPhoto5()) ? null
							: oss.getUrl(bucket, e.getPhoto5(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto6())) {
					array.add(isEmpty(e.getPhoto6()) ? null
							: oss.getUrl(bucket, e.getPhoto6(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto7())) {
					array.add(isEmpty(e.getPhoto7()) ? null
							: oss.getUrl(bucket, e.getPhoto7(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto8())) {
					array.add(isEmpty(e.getPhoto8()) ? null
							: oss.getUrl(bucket, e.getPhoto8(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto9())) {
					array.add(isEmpty(e.getPhoto9()) ? null
							: oss.getUrl(bucket, e.getPhoto9(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				if (!isEmpty(e.getPhoto10())) {
					array.add(isEmpty(e.getPhoto10()) ? null
							: oss.getUrl(bucket, e.getPhoto10(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				ExpertRead expertRead = new ExpertRead(array, e);
				GoodBookRecordVo goodBookRecord = goodBookRecordService.getGoodBookRecord(uid,
						String.valueOf(e.getWorkId()), 1);
				if (null != goodBookRecord) {
					expertRead.setCharpterId(String.valueOf(goodBookRecord.getCharpterId()));
				} else {
					expertRead.setCharpterId(String.valueOf(e.getBeginChapterId()));
				}
				ChapterConfigVo c = chapterConfigService.getChapterConfig(e.getBeginChapterId(), e.getEndChapterId());
				RecordConfigVo r = recordConfigService.getRecordConfig(c.getBeginWordId(), c.getEndWordId());
				expertRead.setFile(r.getFile());
				ExpertReadList.add(expertRead);
			}
			// JSONObject json = new JSONObject();
			// json.put("expertReadingList", ExpertReadList);
			return Message(SUCCESS, "搜索佳作列表成功", ExpertReadList);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "搜索佳作列表失败");
		}
	}

	/**
	 * 返回用户读到那个章节
	 * 
	 * @param req
	 * @param resp
	 * @param uid
	 *            用户id
	 * @return
	 */
	@RequestMapping("/getUserGoodBook")
	@ResponseBody
	public JSON getUserGoodBook(HttpServletRequest req, HttpServletResponse resp, Integer uid) {
		try {
			if (null == uid) {
				return Message(ERROR, "未传用户id", null);
			}
			List<GoodBookRecordVo> GoodBookRecordList = goodBookRecordService.getGoodBookRecordList(uid);
			if (GoodBookRecordList.size() > 0) {
				GoodBookRecordVo GoodBookRecord = GoodBookRecordList.get(0);
				JSONObject obj = new JSONObject();
				if (GoodBookRecord.getType() == 1) {
					ExpertReadingVo e = expertReadingService.getExpertReading(GoodBookRecord.getWorkId());
					String url = isEmpty(e.getPhoto1()) ? null
							: oss.getUrl(bucket, e.getPhoto1(), new Date(new Date().getTime() + 3600 * 1000 * 12));
					e.setPhoto1(url);
					JSONArray array = new JSONArray();
					if (url != null) {
						array.add(0, url);
					}
					if (!isEmpty(e.getPhoto2())) {
						array.add(1, isEmpty(e.getPhoto2()) ? null
								: oss.getUrl(bucket, e.getPhoto2(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
					}
					if (!isEmpty(e.getPhoto3())) {
						array.add(2, isEmpty(e.getPhoto3()) ? null
								: oss.getUrl(bucket, e.getPhoto3(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
					}
					if (!isEmpty(e.getPhoto4())) {
						array.add(3, isEmpty(e.getPhoto4()) ? null
								: oss.getUrl(bucket, e.getPhoto4(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
					}
					if (!isEmpty(e.getPhoto5())) {
						array.add(4, isEmpty(e.getPhoto5()) ? null
								: oss.getUrl(bucket, e.getPhoto5(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
					}
					if (!isEmpty(e.getPhoto6())) {
						array.add(5, isEmpty(e.getPhoto6()) ? null
								: oss.getUrl(bucket, e.getPhoto6(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
					}
					if (!isEmpty(e.getPhoto7())) {
						array.add(6, isEmpty(e.getPhoto7()) ? null
								: oss.getUrl(bucket, e.getPhoto7(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
					}
					if (!isEmpty(e.getPhoto8())) {
						array.add(7, isEmpty(e.getPhoto8()) ? null
								: oss.getUrl(bucket, e.getPhoto8(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
					}
					if (!isEmpty(e.getPhoto9())) {
						array.add(8, isEmpty(e.getPhoto9()) ? null
								: oss.getUrl(bucket, e.getPhoto9(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
					}
					if (!isEmpty(e.getPhoto10())) {
						array.add(9,
								isEmpty(e.getPhoto10()) ? null
										: oss.getUrl(bucket, e.getPhoto10(),
												new Date(new Date().getTime() + 3600 * 1000 * 12)));
					}
					ExpertRead expertRead = new ExpertRead(array, e);
					ChapterConfigVo c = chapterConfigService.getChapterConfig(e.getBeginChapterId(),
							e.getEndChapterId());
					RecordConfigVo r = recordConfigService.getRecordConfig(c.getBeginWordId(), c.getEndWordId());
					expertRead.setFile(r.getFile());
					expertRead.setCharpterId(GoodBookRecord.getCharpterId());
					obj.put("expertRead", expertRead);
					obj.put("type", "1");
					return Message(SUCCESS, "获取用户最近播放佳作记录成功", obj);
				} else {
					obj.put("GoodBookRecord", GoodBookRecord);
					obj.put("type", "2");
					return Message(SUCCESS, "获取用户最近播放作品记录成功", obj);
				}
			} else {
				return Message(SUCCESS, "获取用户最近播放记录成功", null);
			}
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "获取用户最近播放记录异常");
		}

	}

	/**
	 * 查询佳作相关信息
	 * 
	 * @param req
	 * @param resp
	 * @param uid
	 *            用户id
	 * @return
	 */
	@RequestMapping("/getGoodBook")
	@ResponseBody
	public JSON getGoodBook(HttpServletRequest req, HttpServletResponse resp, Integer uid, String workId) {
		try {
			if (null == uid) {
				return Message(ERROR, "未传用户id", null);
			}
			if (null == workId) {
				return Message(ERROR, "未传作品id", null);
			}
			ExpertReadingVo e = expertReadingService.getExpertReading(workId);
			String url = isEmpty(e.getPhoto1()) ? null
					: oss.getUrl(bucket, e.getPhoto1(), new Date(new Date().getTime() + 3600 * 1000 * 12));
			e.setPhoto1(url);
			JSONArray array = new JSONArray();
			if (!isEmpty(e.getPhoto2())) {
				array.add(0, isEmpty(e.getPhoto2()) ? null
						: oss.getUrl(bucket, e.getPhoto2(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			if (!isEmpty(e.getPhoto3())) {
				array.add(1, isEmpty(e.getPhoto3()) ? null
						: oss.getUrl(bucket, e.getPhoto3(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			if (!isEmpty(e.getPhoto4())) {
				array.add(2, isEmpty(e.getPhoto4()) ? null
						: oss.getUrl(bucket, e.getPhoto4(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			if (!isEmpty(e.getPhoto5())) {
				array.add(3, isEmpty(e.getPhoto5()) ? null
						: oss.getUrl(bucket, e.getPhoto5(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			if (!isEmpty(e.getPhoto6())) {
				array.add(4, isEmpty(e.getPhoto6()) ? null
						: oss.getUrl(bucket, e.getPhoto6(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			if (!isEmpty(e.getPhoto7())) {
				array.add(5, isEmpty(e.getPhoto7()) ? null
						: oss.getUrl(bucket, e.getPhoto7(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			if (!isEmpty(e.getPhoto8())) {
				array.add(6, isEmpty(e.getPhoto8()) ? null
						: oss.getUrl(bucket, e.getPhoto8(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			if (!isEmpty(e.getPhoto9())) {
				array.add(7, isEmpty(e.getPhoto9()) ? null
						: oss.getUrl(bucket, e.getPhoto9(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			if (!isEmpty(e.getPhoto10())) {
				array.add(8, isEmpty(e.getPhoto10()) ? null
						: oss.getUrl(bucket, e.getPhoto10(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			ExpertRead expertRead = new ExpertRead(array, e);
			ChapterConfigVo c = chapterConfigService.getChapterConfig(e.getBeginChapterId(), e.getEndChapterId());
			RecordConfigVo r = recordConfigService.getRecordConfig(c.getBeginWordId(), c.getEndWordId());
			expertRead.setFile(r.getFile());
			GoodBookRecordVo goodBookRecord = goodBookRecordService.getGoodBookRecord(uid, workId, 1);
			if (null != goodBookRecord) {
				expertRead.setCharpterId(goodBookRecord.getCharpterId());
			} else {
				expertRead.setCharpterId(String.valueOf(e.getBeginChapterId()));
			}
			return Message(SUCCESS, "获取用户佳作记录成功", expertRead);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "获取用户佳作记录异常");
		}

	}

}
